/**
 * Created by renzhiqiang on 17/5/10.
 */
/**
 * Created by renzhiqiang on 17/5/8.
 */
import React, {PropTypes} from 'react'
import { Form, Icon, Input, Button, Select, Spin, Row, Col, DatePicker, Modal} from 'antd';
import {connect} from  'dva';
import {hashHistory} from  'dva/router';
import { Breadcrumb, RegionCascader, BoxLabel, FileUpload} from './../../components/cor';
import style from './index.less';
const FormItem = Form.Item;
const Option = Select.Option;

function add({dispatch, histroy, add, form}) {
  const {detailLoading, foundStage, address, detail} = add;
  const { getFieldDecorator, getFieldsError, getFieldsValue, validateFields } = form;
  const actionTypeHead = 'add/';
  if (!add) {
    return null;
  }
  const Breadcrumbs = {
    dispatch,
    data: [
      {item:'首页'},
      {item:'列表'},
      {item:'新增'}
    ]
  };
  const submitHandle = () => {
    validateFields((errors) => {
      if (errors) {
        return
      }
      console.log(address);
      const data = {
        ...getFieldsValue()
      };
      // 处理街道地址
      address.address = data.address;
      delete data["date-picker"];
      // const keys = Object.keys(data);
      // keys.forEach(x => {
      //   if (data[x] && data[x].hasOwnProperty('_isUTC') && data[x]._d && data[x]._d instanceof Date) {
      //     data[x] = data[x].format(timeFormatMap[] || 'YYYY-MM-DD');
      //   }
      // });
      let isRefused = 0;  // 是否被拒绝    0否  1是
      if (false) {
        isRefused = 1;
        dispatch({
          type: `${actionTypeHead}detailUpdate`,
          payload: {
            ...data,
            address,
            isRefused
          }
        })
      } else {
        dispatch({
          type: `${actionTypeHead}add`,
          payload: {
            ...data,
            address,
            isRefused
          }
        })
      }

    })
  };
  const cancelHandle = () => {
    Modal.confirm({
      title: '确定放弃新增数据?',
      content: null,
      onOk() {
        hashHistory.goBack();
      },
      onCancel() {
      },
    });
  };
  const handleRegionId = (val, data) => {
    console.log('-------', val, data);
    if (data.length > 1) {
      address.adcode = val[val.length - 1];  // 所在市区编号
      address.adname = data[val.length - 1].label; // 所在市区
      address.cityCode = val[val.length - 2];  // 所在城市编号
      address.city = data[val.length - 2].label;// 城市
      address.province = data[0].label;  // 省
    }
  };
  const disabledDate = (current) =>{
    return current && current.valueOf() < Date.now();
  };
  const fileUploadProps1 = {
    // accept: 'doc|docx|xls|xlsx',
    accept: '',
    labelText: '方案建议书',
    countLimit: 1,
    defaultList: [],
    getList: list => {
      console.log(JSON.stringify(list));
      let ids = []
      for (let i = 0; i < list.length; i++) {
        ids.push(list[i].response.fId);
      }
      dispatch({
        type: `${actionTypeHead}updateState`,
        payload: {
          introductionId: ids,
        }
      });
    }
  };
  function onChange(date, dateString) {
    console.log(date, dateString);
  };
  return (
    <div>
      <Breadcrumb {...Breadcrumbs} ></Breadcrumb>
      <div className={style.content}>
        <Spin spinning={detailLoading} delay={200}>
          <div className={style.tabContent}>
            <Row>
              <Form layout="horizontal">
                <Row gutter={16}>
                  <Col span={12}>
                    <FormItem label="项目名称：" hasFeedback>
                      {getFieldDecorator('fundName',{ rules: [{type: 'email', message: 'The input is not valid E-mail!'}]})(<Input placeholder="请输入项目名称"/>)}
                    </FormItem>
                  </Col>
                  <Col span={12}>
                    <FormItem label="课题：" hasFeedback>
                      {getFieldDecorator('name')(<Input placeholder="请输入课题名称"/>)}
                    </FormItem>
                  </Col>
                </Row>
                <Row gutter={16}>
                  <Col className="gutter-row" span={12}>
                    <FormItem label="管理公司" hasFeedback>
                      {getFieldDecorator('companyId', {
                        initialValue: ''})(
                        <Select
                          showSearch
                          allowClear
                          multiple={false}
                          style={{width: '100%'}}
                          placeholder="请选择基金类型"
                          optionFilterProp="desc"
                        >
                          {
                            foundStage.map((item, key) => {
                                return <Option key={key + ''} value={item.value + ''}
                                               desc={item.text}>{item.text}</Option>
                              }
                            )}
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                  <Col className="gutter-row" span={12}>
                    <FormItem label="管理公司" hasFeedback>
                      {getFieldDecorator('companyIDS', {initialValue: ["17", "19"]})(
                        <Select
                          mode="tags"
                          showSearch
                          style={{ width: '100%' }}
                          placeholder="Please select"
                        >
                          {
                            foundStage.map((item, key) => {
                                return <Option key={key + ''} value={item.value + ''}
                                               desc={item.text}>{item.text}</Option>
                              }
                            )}
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                </Row>
                <Row gutter={16}>
                  <Col className="gutter-row" span={12}>
                    <FormItem label="地址" hasFeedback>
                      <RegionCascader handle={handleRegionId}/>
                    </FormItem>
                  </Col>
                  <Col className="gutter-row" span={12}>
                    <FormItem label="地址" hasFeedback>
                      {getFieldDecorator('date-picker')(
                        <DatePicker
                          disabledDate={disabledDate}
                          onChange={onChange}
                        />
                      )}
                    </FormItem>
                  </Col>
                </Row>
              </Form>
              <div className="splitLine"></div>
              <BoxLabel text="上传附件"/>
              <FileUpload {...fileUploadProps1} key="1"/>
              <div className="splitLine wide"></div>
              <div style={{paddingTop: '24px'}}>
                <Button size={'large'} style={{marginRight: '20px'}} onClick={cancelHandle}>取消</Button>
                <Button size={'large'} type="primary" onClick={submitHandle}>提交</Button>
              </div>
            </Row>
          </div>
        </Spin>
      </div>
    </div>

  )
}
const state = ({add}) => {
  return {add}
};

export  default connect(state)(Form.create()(add));
